package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parallelandroid.entity.User;
import com.example.parallelandroid.utils.EncryptUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AccountActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tvPhone;
    private EditText edtOldPwd,edtNewPwd,edtConfirmPwd;
    private Button btnUpdatePwd;
    private String oldPwd,phone;
    private String newPwd;
    private String userId;
    private SharedPreferences user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        btnUpdatePwd = findViewById(R.id.btn_updatepwd);
        tvPhone = findViewById(R.id.tv_number);
        edtOldPwd = findViewById(R.id.edt_oldpwd);
        edtNewPwd = findViewById(R.id.edt_newpwd);
        edtConfirmPwd = findViewById(R.id.edt_confirmpwd);
        toolbar = findViewById(R.id.accounttoolbar);

        initView();

        edtNewPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String pwd = edtNewPwd.getText().toString();
                if(TextUtils.isEmpty(pwd)&&"".equals(pwd)){
                    edtNewPwd.setError("请输入密码");
                }else {
                    if(pwd.length()>=8&&pwd.length()<=15){

                    }else {
                        edtNewPwd.setError("请输入8到15位密码，可包含大小写字母和数字和特殊字符");

                    }
                }
            }
        });

        // 为ToolBar添加返回键
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 添加默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); // 设置返回键可用
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 返回
            }
        });

        // 获取SharedPreferences
        user = getSharedPreferences("user", MODE_PRIVATE);
        userId = user.getString("userId", "userId");

        //获取数据库数据
        getData();

        //按钮点击事件
        //更改密码
        btnUpdatePwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkHttpClient okHttpClient = new OkHttpClient();
                User user = new User();
                user.setUserId(userId);
                user.setUserName(phone);
                //编辑框中输入的密码进行加密
                String edtOld = EncryptUtils.encrypt(edtOldPwd.getText().toString());

                //如果输入的旧密码与数据库存入的密码一致
                if (edtOld.equals(oldPwd)){
                    //如果新密码与旧密码不一样
                    if(!edtNewPwd.getText().toString().equals(edtOldPwd.getText().toString())){
                        //并且重复确认密码正确
                        if (edtNewPwd.getText().toString().equals(edtConfirmPwd.getText().toString())){
                            //如果设置密码符合规范编辑框中输入新密码进行加密
                            if (checkPassword(edtNewPwd.getText().toString())){
                                newPwd = EncryptUtils.encrypt(edtNewPwd.getText().toString());
                                //将加密后的新密码存入对象
                                user.setPassword(newPwd);
                                Constant.logger.info("开始向服务端传输用户数据user, userId = " + user.getUserId());
                                Gson gson = new Gson();
                                String json = gson.toJson(user);
                                //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
                                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
                                //创建请求对象（Request）
                                Request request = new Request.Builder()
                                        .url(Constant.BASE_URL+"user/createUser")
                                        .post(requestBody)
                                        .build();
                                Call call = okHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                        Constant.logger.warn("向服务端传输用户数据user: 失败", e);
                                    }

                                    @Override
                                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                        String json = response.body().string();
                                        JSONObject jsonObject = null;
                                        try {
                                            jsonObject = new JSONObject(json);
                                            String code = jsonObject.getString("code");
                                            String msg = jsonObject.getString("msg");
                                            Constant.logger.info("服务端Response: " + msg);
                                            Intent newIntent = new Intent(AccountActivity.this,MainFromActivity.class);
                                            startActivity(newIntent);
                                            finish();
                                            Looper.prepare();
                                            Toast.makeText(AccountActivity.this, "修改密码成功", Toast.LENGTH_SHORT).show();
                                            Looper.loop();
                                        } catch (JSONException e) {
                                            Constant.logger.error("解析服务端Response: 失败", e);
                                        }
                                    }
                                });
                            }else{
                                edtNewPwd.setText("");
                                edtConfirmPwd.setText("");
                                Toast toast=Toast.makeText(getApplicationContext(), "您设置的密码不符合规范，请依据要求设置密码", Toast.LENGTH_SHORT);
                                toast.show();
                            }
                        }else{
                            edtConfirmPwd.setText("");
                            Constant.logger.info("用户修改密码失败: 重复输入修改密码错误");
                            Toast toast=Toast.makeText(getApplicationContext(), "请确认修改密码输入正确", Toast.LENGTH_SHORT);
                            toast.show();
                        }

                    }else {
                        edtNewPwd.setText("");
                        edtConfirmPwd.setText("");
                        Constant.logger.info("用户修改密码失败: 新密码与旧密码一致");
                        Toast toast=Toast.makeText(getApplicationContext(), "新旧密码一样，不能更改", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                }else{
                    edtOldPwd.setText("");
                    Constant.logger.info("用户修改密码失败: 旧密码输入错误");
                    Toast toast=Toast.makeText(getApplicationContext(), "旧密码输入错误,请重新输入", Toast.LENGTH_SHORT);
                    //toast位置居中
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }


            }
        });
    }

    //从数据库获取数据  id获取全局变量里边的
    private void getData() {
        Constant.logger.info("从服务端获取用户账号密码数据 开始");
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"user/findUserById?id="+userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.error("从服务端获取用户账号密码数据: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String perdata = response.body().string();
                User user = null;
                try {
                    user = new Gson().fromJson(new JSONObject(perdata).getJSONObject("data").toString(),new TypeToken<User>(){}.getType());
                    String msg = new JSONObject(perdata).getString("msg");
                    Constant.logger.warn("服务端Response: " + msg);
                } catch (JSONException e) {
                    Constant.logger.error("解析服务端Response: 失败", e);
                }
                phone = user.getUserName();
                tvPhone.setText(phone);
                oldPwd = user.getPassword();
//                Looper.prepare();
//                Toast.makeText(AccountActivity.this, ""+oldPwd, Toast.LENGTH_SHORT).show();
//                Looper.loop();
            }
        });
    }

    //判断密码是否符合规范
    private boolean checkPassword(String password2) {
        boolean capitalFlag = false;
        boolean lowerCaseFlag = false;
        boolean numberFlag = false;
        boolean numLength = false;
        boolean res = false;
        // 获取用户输入的新密码
        String newPwd = password2;
        for (int i=0; i<newPwd.length(); i++) {
            Character ch = newPwd.charAt(i);
            if( Character.isDigit(ch)) {
                numberFlag = true;
            } else if (Character.isUpperCase(ch)) {
                capitalFlag = true;
            } else if (Character.isLowerCase(ch)) {
                lowerCaseFlag = true;
            }
        }
        if (newPwd.length() >= 8 && newPwd.length() <= 15){
            numLength = true;
        }
        if(numberFlag && capitalFlag && lowerCaseFlag && numLength) {
            res = true;
        }
        return res;
    }

    //判断密码强度
    private void initView() {
        LinearLayout passLayout = findViewById(R.id.passwordLayout);
        View passView1 = findViewById(R.id.passwordView1);
        View passView2 = findViewById(R.id.passwordView2);

        edtNewPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().length() > 0){
                    if(s.toString().length() == 1)
                        passLayout.setVisibility(View.VISIBLE);
                    switch (checkPassWord(s.toString())){
                        case 1:
                            passView1.setVisibility(View.GONE);
                            passView2.setVisibility(View.GONE);
                            break;
                        case 2:
                            passView1.setVisibility(View.VISIBLE);
                            passView2.setVisibility(View.GONE);
                            break;
                        case 3:
                            passView2.setVisibility(View.VISIBLE);
                            break;
                    }
                }else{
                    passLayout.setVisibility(View.GONE);
                }
            }
        });
    }

    private int checkPassWord(String passwordStr) {
        String regexZ = "\\d*";
        String regexS = "[a-zA-Z]+";
        String regexT = "\\W+$";
        String regexZT = "\\D*";
        String regexST = "[\\d\\W]*";
        String regexZS = "\\w*";
        String regexZST = "[\\w\\W]*";
        int pass = 0;
        if (passwordStr.matches(regexZ)) {
            return 1;
        }
        if (passwordStr.matches(regexS)) {
            return 1;
        }
        if (passwordStr.matches(regexT)) {
            return 1;
        }
        if (passwordStr.matches(regexZT)) {
            return 2;
        }
        if (passwordStr.matches(regexST)) {
            return 2;
        }
        if (passwordStr.matches(regexZS)) {
            return 2;
        }
        if (passwordStr.matches(regexZST)) {
            return 3;
        }
        return pass;
    }



}